import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const TimeUtils = require('../../utils/timeUtil');
const httpExt = require('../../utils/request');

// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
  avatarUrl: "",
  isGetUserInfo: false,
  imgUrls: [
    {
    link: '/pages/index/index',
    url: '/images/1.1.jpg',
    httpUrl:'https://quanyu-jingqiu.oss-cn-beijing.aliyuncs.com/1.1.jpg'
    }, {
    link: '/pages/list/list',
    url: '/images/1.2.jpg',
    httpUrl: 'https://quanyu-jingqiu.oss-cn-beijing.aliyuncs.com/1.2.jpg'
    }, {
    link: '/pages/list/list',
    url: '/images/1.3.jpg',
    httpUrl: 'https://quanyu-jingqiu.oss-cn-beijing.aliyuncs.com/1.3.jpg'
    },
    {
      link: '/pages/list/list',
      url: '/images/2.1.jpg',
      httpUrl:'https://quanyu-jingqiu.oss-cn-beijing.aliyuncs.com/2.1.jpg'
    },
    {
      link: '/pages/list/list',
      url: '/images/2.2.jpg',
      httpUrl: 'https://quanyu-jingqiu.oss-cn-beijing.aliyuncs.com/2.2.jpg'
    },
    {
      link: '/pages/list/list',
      url: '/images/2.3.jpg',
      httpUrl: 'https://quanyu-jingqiu.oss-cn-beijing.aliyuncs.com/2.3.jpg'
    }
    ],
    swiperheight :1500,
    nickName: '',
    avatarUrl: '',
    indicatorDots: false, //小点
    indicatorColor: "white",//指示点颜色
    activeColor: "coral",//当前选中的指示点颜色
    autoplay: true, //是否自动轮播
    interval: 5000, //间隔时间
    duration: 1000, //滑动时间
    expire: false,
    alreadyClick: false,
    readonly: true,
    phoneNumber: '',
    userName: '',
    userCode: '',
    currentUserAvatarUrl:'',
    currentUserNickName: '',
    checkAppointment: false,
    days: 0,
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 页面加载事件
   */
  onLoad() {
    //计算婚礼剩余日
    this.setData({
      days: `${TimeUtils.Jh_getDifferenceDays(
        TimeUtils.Jh_timeStampToNo0Time(new Date().getTime(), '{y}-{m}-{d}'), TimeUtils.Jh_timeStampToNo0Time(1677297600000, '{y}-{m}-{d}') 
      )} 天`
    });
  },

  /**
   * 页面展示事件
   */
  onShow(){
    //获取用户信息
    this.getByCode();
    //计算是否截止报名
    this.computeExpire();
  },

  /**
   * 打开婚礼位置地图
   */
  launchLocation:function(){
    wx.openLocation({
      latitude: 31.372182,
      longitude: 118.449923,
      scale: 18,
      name: '芜湖新华联丽景酒店',
      address: '安徽省芜湖市鸠江区徽州路77号'
    });
  },

  /**
   * 报名参加活动
   */
  modifyUserInfo:function(e){
    this.setData({
      alreadyClick: true
    });

    //收集参数信息
    var data = {};
    data.userName = this.data.userName;
    data.phoneNumber = this.data.phoneNumber;
    data.code = this.data.userCode

    //调用报名接口
    var that = this;
    httpExt.post("/sign_up",data).then(res => {
      if(res.data.data){
        that.setData({
          alreadyClick: false
        });
        wx.showModal({
          title: '报名成功',
          showCancel: false,
          content: '恭喜您报名成功！游戏会在开始前通过微信消息的方式推送至您的手机，请注意查收。',
          success (wxRes) {
            if (wxRes.confirm) {
              var pn = that.getTel(that.data.phoneNumber);
              that.setData({
                phoneNumber: pn,
                readonly: true
              });
              wx.requestSubscribeMessage({
                tmplIds: ['8ZWuucvh9U0LsR6yMCVBTuJkLsF0c2_y1d3zwWfZ62U'],
                success (res) {
                  if(res.errMsg == 'requestSubscribeMessage:ok'){
                    that.doCheckAppointment();
                  }
                },
                complete:function(){
                  that.setData({
                    alreadyClick: false
                  });
                }
              });
            }
          }
        });
      }
    });
  },

  /**
   * 用户登录
   */
  login:function(){
    wx.login({
      success (res) {
        if (res.code) {
          wx.setStorageSync("code", res.code);
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
  },

  /**
   * 保存输入框中的真实姓名值信息
   */
  setName:function(value){
    this.setData({
      userName : value.detail
    });
  },

  /**
   * 保存输入框中的手机号信息
   */
  setPhoneNumber:function(value){
    this.setData({
      phoneNumber : value.detail
    });
  },

  /**
   * 检查用户是否已经预约
   */
  doCheckAppointment:function(){
    var that = this;
    httpExt.post("/check_appointment", {"code": that.data.userCode}).then(res => {
      that.setData({
        checkAppointment: !res.data.data,
        readonly: res.data.data
      })
    });
  },

  /**
   * 获取带*号的隐私手机号
   * @param {string} tel 
   */
  getTel:function(tel){
      var a= tel.substring(0, 3)+"****"+tel.substr(tel.length-4);
      console.log(a);
      return a;
  },

  /**
   * 计算是否已经截止报名
   */
  computeExpire:function(){
    if(TimeUtils.Jh_getTimeStamp() > TimeUtils.Jh_convertTimeStamp('2023-2-24 23:00:00')){
      this.setData({
        expire: true
      })
    }
  },

  /**
   * 根据code获取用户信息
   */
  getByCode:function(){
    var that = this;
    wx.login({
      success (res) {
        if (res.code) {
          //发起网络请求
          httpExt.get("/info/" + res.code).then(res => {
            if(res.data.data){
              that.setData({
                userCode: res.data.data.userCode,
                readonly: true
              });
              if(res.data.data.phoneNumber){
                that.setData({
                  phoneNumber: that.getTel(res.data.data.phoneNumber),
                  userName: res.data.data.userName,
                  readonly: true
                });
              } else {
                that.doCheckAppointment();
                that.setData({
                  readonly: false
                });
              }
            } else {
              that.getUserInfo();
            }
          });
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
  },

  /**
   * 获取用户信息
   */
  getUserInfo:function(){
    wx.showModal({
      title: '获取信息',
      showCancel: true,
      content: '我们需要获取您的微信头像和昵称信息',
      success (wxRes) {
        if(wxRes.cancel){
          wx.exitMiniProgram({});
        }
        if (wxRes.confirm) {
          wx.navigateTo({
            url: '../initUserProfile/initUserProfile'
          })
        }
      }
    });
  },

  /**
   * 展示照片信息
   * @param {object} e 
   */
  viewPhoto:function(e){
    console.log(this.data.imgUrls[1].httpUrl)
    var httpUrl = e.currentTarget.dataset.url;
    var index = e.currentTarget.dataset.index;
    var httpUrlArray = [];
    for (let index = 0; index < this.data.imgUrls.length; index++) {
      httpUrlArray[index] = this.data.imgUrls[index].httpUrl;
    }

    wx.previewImage({
      current: httpUrl, // 当前显示图片的 http 链接
      current: index,
      urls: httpUrlArray // 需要预览的图片 http 链接列表
    })
  },

  /**
   * 验证报名参数信息
   */
  verifySignUpParam(){
    var phone = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    var regName = /^[\u4e00-\u9fa5]{2,4}$/;
    if(!phone.test(this.data.phoneNumber)){
      Toast.fail('手机号格式不正确，请重新填写');
      this.setData({
        alreadyClick: false
      });
      return false;
    }

    if(!regName.test(this.data.userName)){
      Toast.fail('真实姓名验证不通过，请重新填写');
      this.setData({
        alreadyClick: false
      });
      return false;
    }
  }
});
